from rest_framework import serializers
from goods.models import SKU


class CartSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品id')
    count = serializers.IntegerField(min_value=1, label='商品数量')
    selected = serializers.BooleanField(default=True, label='是否勾选')

    def validate(self, attrs):
        try:

            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        if attrs['count'] > sku.stock:
            return serializers.ValidationError('商品库存不足')

        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    count = serializers.IntegerField(min_value=1, label='商品数量')
    selected = serializers.BooleanField(default=True, label='是否勾选')

    class Meta:
        model = SKU
        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')


class CartDelSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1, label='商品id')

    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return attrs


class CartSelectedSerializer(serializers.Serializer):
    selected = serializers.BooleanField()

